package com.example.config.securityAllconfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.service.IUserService;
import com.example.util.JwtUtil;
import com.example.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class MyAuthetcationSucessHandle implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获取用户信息
        UserDetails principal = (UserDetails)authentication.getPrincipal();
        String username = principal.getUsername();
        System.out.println("我在这里测试username是否为空");
        //判断用户状态
        User login = userService.getOne(new QueryWrapper<User>().eq("phone", username));
        if(login.getStatus().equals(0)){
            Result r1 = Result.builder()
                    .flag(false)
                    .msg("该用户已被封号,无法登录")
                    .data(login.getUsername())
                    .build();
            printToken(httpServletRequest, httpServletResponse,r1);
            return;
        }
        //判断重复登录
        if(login.getStatus().equals(2)){
            Result r1 = Result.builder()
                    .flag(false)
                    .msg("该用户已登录,请不要尝试重复登录！")
                    .data(login.getUsername())
                    .build();
            printToken(httpServletRequest, httpServletResponse,r1);
            return;
        }
        Map map=new HashMap();
        map.put("username",username);

        Collection<? extends GrantedAuthority> authorities1 = principal.getAuthorities();
        List<GrantedAuthority> authorities=new ArrayList<>();
        authorities.addAll(authorities1);

        List<String> authList=authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        String token = jwtUtil.creatJWT(map, authList);

        Result build = Result.builder()
                .flag(true)
                .msg("jwt生成成功")
                .data(token)
                .build();

        stringRedisTemplate.opsForValue().set("logintoken"+token,objectMapper.writeValueAsString(authentication),12, TimeUnit.HOURS);


        printToken(httpServletRequest, httpServletResponse,build);
        //登录成功修改用户状态
        login.setStatus(2);
        userService.updateById(login);

    }

    public void printToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Result build) throws IOException {
        String s = objectMapper.writeValueAsString(build);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(s);
        writer.flush();

    }
}
